package com.shareyi.netty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * client handler
 *
 * @author zhangshibin
 * @since 2018/9/21
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);

    private final byte[] reqBytes;

    public EchoClientHandler() throws UnsupportedEncodingException {
       reqBytes = "b".getBytes("UTF-8");
       // firstMessage.writeBytes(reqBytes);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for(int i = 0; i< 100; i++){
            ByteBuf firstMessage = Unpooled.buffer(reqBytes.length);
            firstMessage.writeBytes(reqBytes);
            if(i%50==0){
                ctx.flush();
                Thread.sleep(200);
            }
            ctx.write(firstMessage);
        }
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("client channelRead");
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req,"UTF-8");
        logger.info("echo msg = {}", body);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("client channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("exception caught", cause);
        ctx.close();
    }
}
